package io.renren.modules.alarm.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.alarm.dao.GuardDao;
import io.renren.modules.alarm.entity.GuardEntity;
import io.renren.modules.alarm.service.GuardService;


@Service("guardService")
public class GuardServiceImpl extends ServiceImpl<GuardDao, GuardEntity> implements GuardService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String)params.get("username");

        IPage<GuardEntity> page = this.page(
                new Query<GuardEntity>().getPage(params),
                new QueryWrapper<GuardEntity>()
                        .like(StringUtils.isNotBlank(username),"user_name", username)
        );

        return new PageUtils(page);
    }

    @Override
    public GuardEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<GuardEntity>().eq("user_phone", mobile));
    }

    @Override
    public long login(LoginForm form) {
        GuardEntity guard = queryByMobile(form.getMobile());
        Assert.isNull(guard, "手机号或密码错误");

        //密码错误
        if(!guard.getUserPwd().equals(DigestUtils.sha256Hex(form.getPassword()))){
            throw new RRException("手机号或密码错误");
        }

        return guard.getUserId();
    }


}